package com.kun.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.stereotype.Controller;

import com.google.gson.Gson;
import com.kun.entity.CarEntity;
import com.kun.server.CarServer;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@Namespace("/")
public class CarAaction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private CarEntity carEntity;
	
	@Resource(name="CarServerImpl")
	private CarServer carServer;

	/**
	 * 添加车辆
	 * 添加成功返回到<br/>
	 * 失败放回到error页面
	 */
	@Action(value="addCar",results={
			@Result(name="success",location="/index.jsp"),
			@Result(name="error",location="/error.jsp")
	})
	public String addCar(){
		int customerid = (Integer)ServletActionContext.getRequest()
						.getSession().getAttribute("customerid");
		return carServer.addCar(carEntity,customerid);
	}
	/**
	 * 查询车辆信息
	 * @return
	 */
	public String getCarInfo(){
		int customerid = (Integer)ServletActionContext.getRequest()
						.getSession().getAttribute("customerid");
		List<CarEntity> carInfo = carServer.getCarInfo(customerid);
		ServletActionContext.getRequest().setAttribute("carInfo",carInfo);
		return SUCCESS;
	}
	
	/**
	 * 根据车牌获取车辆信息(车架，发动机)ajax
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public void getCarInfoByCarId() throws UnsupportedEncodingException{
		HttpServletRequest request = ServletActionContext.getRequest();
		String carId = request.getParameter("carId");
		String carId1 = URLDecoder.decode(carId,"UTF-8");
		carId = URLDecoder.decode(carId1,"UTF-8");
		System.out.println(carId);
		List<CarEntity> carInfoByCarId = carServer.getCarInfoByCarId(carId);
		String carVIN = carInfoByCarId.get(0).getCarVIN();//车架
		String carEngineNo = carInfoByCarId.get(0).getCarEngineNo();//发动机
		Map<String,String> map = new HashMap<String,String>();
		map.put("carVIN",carVIN);
		map.put("carEngineNo",carEngineNo);
		Gson gson = new Gson();
		String json = gson.toJson(map);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		//获得输出流
		PrintWriter pw;
		try {
			pw = response.getWriter();
			//将数据写入输出流
			pw.write(json);
			//清楚数据流缓冲区
			pw.flush();
			//关闭输出流
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public CarEntity getCarEntity() {
		return carEntity;
	}
	public void setCarEntity(CarEntity carEntity) {
		this.carEntity = carEntity;
	}
	
}
